<script setup lang="ts">
import type { AuthenticationInformationProps } from '@croco/framework/libraries';

import { SliderCaptcha } from '@croco/framework/libraries';
import { $t } from '@croco/framework/locales';

defineOptions({ name: 'LoginForm' });

withDefaults(
    defineProps<{
        captchaImage?: string;
        rules: {};
    }>(),
    {
        captchaImage: undefined,
    },
);

const emit = defineEmits(['captcha']);

const form = defineModel<AuthenticationInformationProps>({
    default: {
        username: undefined,
        password: undefined,
    },
});

const loginFormRef = ref();

const handleCaptcha = () => {
    emit('captcha');
};

defineExpose({
    validate: (validate: (status: boolean) => void) => loginFormRef.value.validate(validate),
});
</script>

<template>
    <el-form ref="loginFormRef" :model="form" :rules="rules">
        <el-form-item prop="username">
            <el-input v-model="form.username" :placeholder="$t('authentication.username')" clearable prefix-icon="el-icon-user" />
        </el-form-item>
        <el-form-item prop="password">
            <el-input v-model="form.password" :placeholder="$t('authentication.password')" clearable prefix-icon="el-icon-lock" show-password />
        </el-form-item>
        <el-form-item v-if="captchaImage" class="login-captcha" prop="code">
            <el-input v-model="form.code" :placeholder="$t('authentication.code')" prefix-icon="el-icon-key" style="width: 100%">
                <template #append>
                    <el-image :src="captchaImage" style="width: 100%; height: var(--el-input-height)" @click="handleCaptcha()" />
                </template>
            </el-input>
        </el-form-item>
        <el-form-item v-else prop="code">
            <SliderCaptcha v-model="form.code" />
        </el-form-item>
    </el-form>
</template>

<style lang="scss" scoped>
.login-captcha {
    :deep(.el-input-group__append) {
        padding: 1px 3px 1px 1px;
    }
}
</style>
